package com.jackrain.clouddata.oms.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.clouddata.sys.sender.BackSender;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class OrderBackDao {

    @Transactional
    public void updateSaleOrTranfer(JSONObject jsonObject, String tag, String topic) {
        log.info("---------------------执行入库方法--------------------------");
        String mainTableName = jsonObject.getString("name");
        JSONObject mainValueJo = jsonObject.getJSONObject("value");
        String sonTableName = jsonObject.getJSONArray("item").getJSONObject(0).getString("name");
        JSONArray sonValueArray = jsonObject.getJSONArray("item").getJSONObject(0).getJSONArray("value");
        String queryClinetId = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE TAGNAME=?";
        JSONObject clientIdJo = QueryEngine.getInstance().doQueryObject(queryClinetId, new Object[]{tag});
        Long clientid = clientIdJo.getLong("AD_CLIENT_ID");
        //循环更新子表数据
        for (int i = 0; i < sonValueArray.size(); i++) {
            JSONObject itemJo = sonValueArray.getJSONObject(i);
            //获取条码,单据编号,入库数量,入库金额
            String billNo = itemJo.getString("BILLNO");
            String skuNo = itemJo.getString("SKUNO");
//            int qtyIn = Integer.valueOf(itemJo.getString("QTYIN"));
//            double amtIN = Double.valueOf(itemJo.getString("AMTIN"));
            itemJo.remove("BILLNO");
            itemJo.remove("SKUNO");
            //执行更新子表
            StringBuffer strItemBuf = new StringBuffer("UPDATE " + sonTableName + " SET ");
            List paramList = new ArrayList();
            Set<String> itemKeySet = sonValueArray.getJSONObject(i).keySet();
            //拼接更新语句
            int sum = 0;
            for (String itemkey : itemKeySet) {
                sum++;

                if (itemkey.substring(itemkey.length() - 4, itemkey.length()).equals("DATE")) {
                    paramList.add(TypeUtils.castToDate(itemJo.get(itemkey)));
                    if (sum == itemKeySet.size()) {
                        strItemBuf.append(itemkey + "=? ");
                    } else {
                        strItemBuf.append(itemkey + "=?,");
                    }
                } else if (null == itemJo.get(itemkey) || "".equals(itemJo.get(itemkey))) {
                    if (sum == itemKeySet.size()) {
                        strItemBuf.deleteCharAt(strItemBuf.length()-1);
                    }
                } else {
                    paramList.add(itemJo.get(itemkey));
                    if (sum == itemKeySet.size()) {
                        strItemBuf.append(itemkey + "=? ");
                    } else {
                        strItemBuf.append(itemkey + "=?,");
                    }
                }
            }
            strItemBuf.append(" WHERE BILLNO=? AND SKUNO=? AND AD_CLIENT_ID=?");
            paramList.add(billNo);
            paramList.add(skuNo);
            paramList.add(clientid);
            QueryEngine.getInstance().executeUpdate(strItemBuf.toString(), paramList.toArray());

        }

        //获取主表单号，公司code
        String billNo = mainValueJo.getString("BILLNO");
        String clientCode = mainValueJo.getString("CLIENTCODE");
        mainValueJo.remove("BILLNO");
        mainValueJo.remove("CLIENTCODE");
        //执行更新主表
        StringBuffer strMainBuf = new StringBuffer("UPDATE " + mainTableName + " SET ");
        List paramList = new ArrayList();
        Set<String> mainKeySet = mainValueJo.keySet();
        int sum = 0;
        //拼接更新语句
        for (String mainkey : mainKeySet) {
            sum++;
            if (mainkey.substring(mainkey.length() - 4, mainkey.length()).equals("DATE")) {
                paramList.add(TypeUtils.castToDate(mainValueJo.get(mainkey)));
                if (sum == mainKeySet.size()) {
                    strMainBuf.append(mainkey + "=? ");
                } else {
                    strMainBuf.append(mainkey + "=?,");
                }
            } else if (null == mainValueJo.get(mainkey) || "".equals(mainValueJo.get(mainkey))) {
                if (sum == mainKeySet.size()) {
                    strMainBuf.deleteCharAt(strMainBuf.length()-1);
                }
            } else {
                paramList.add(mainValueJo.get(mainkey));
                if (sum == mainKeySet.size()) {
                    strMainBuf.append(mainkey + "=? ");
                } else {
                    strMainBuf.append(mainkey + "=?,");
                }
            }
        }
        strMainBuf.append(" WHERE BILLNO=? AND CLIENTCODE=?");
        paramList.add(billNo);
        paramList.add(clientCode);
        QueryEngine.getInstance().executeUpdate(strMainBuf.toString(), paramList.toArray());
        //做返回
        BackSender.send(topic, tag, clientid.toString(), billNo);
    }

    @Transactional
    public void insertRetail(JSONObject jsonObject, String tag, String topic) {
        log.info("---------------------执行插入销售退货申请--------------------------");
        String mainTableName = jsonObject.getString("name");
        JSONObject mainValueJo = jsonObject.getJSONObject("value");
        String sonTableName = jsonObject.getJSONArray("item").getJSONObject(0).getString("name");
        JSONArray sonValueArray = jsonObject.getJSONArray("item").getJSONObject(0).getJSONArray("value");
        String queryClinetId = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE TAGNAME=?";
        JSONObject clientIdJo = QueryEngine.getInstance().doQueryObject(queryClinetId, new Object[]{tag});
        Long clientid = clientIdJo.getLong("AD_CLIENT_ID");
        String billno = mainValueJo.getString("BILLNO");
        String countsql = "SELECT COUNT(1) FROM " + mainTableName + " WHERE BILLNO=? AND AD_CLIENT_ID=?";
        int count = QueryEngine.getInstance().doQueryInt(countsql, new Object[]{billno, clientid});
        if (count == 0) {
            //循环插入子表数据
            for (int i = 0; i < sonValueArray.size(); i++) {
                JSONObject itemJo = sonValueArray.getJSONObject(i);
                StringBuffer strItemBuf = new StringBuffer("INSERT INTO " + sonTableName + "(");
                List paramList = new ArrayList();
                Set<String> itemKeySet = sonValueArray.getJSONObject(i).keySet();
                //拼接插入语句
                for (String itemkey : itemKeySet) {
                    if (itemkey.substring(itemkey.length() - 4, itemkey.length()).equals("DATE")) {
                        paramList.add(TypeUtils.castToDate(itemJo.get(itemkey)));
                        strItemBuf.append(itemkey + ",");
                    } else if (null == itemJo.get(itemkey) || "".equals(itemJo.get(itemkey))) {
                    } else {
                        paramList.add(itemJo.get(itemkey));
                        strItemBuf.append(itemkey + ",");
                    }
                }
                strItemBuf.append("ID,AD_CLIENT_ID) VALUES(");
                for (String itemkey : itemKeySet) {
                    if (null == itemJo.get(itemkey) || "".equals(itemJo.get(itemkey))) {

                    }else {
                        strItemBuf.append("?,");
                    }
                }
                strItemBuf.append("?,?)");
                paramList.add(Tools.getSequence(sonTableName));
                paramList.add(clientid);
                QueryEngine.getInstance().executeUpdate(strItemBuf.toString(), paramList.toArray());
            }

            StringBuffer mainStrBuf = new StringBuffer("INSERT INTO " + mainTableName + "(");
            String billNo = mainValueJo.getString("BILLNO");
            List paramList = new ArrayList();
            Set<String> mainKeySet = mainValueJo.keySet();
            //拼接插入语句
            for (String mainkey : mainKeySet) {
                if (mainkey.substring(mainkey.length() - 4, mainkey.length()).equals("DATE")) {
                    paramList.add(TypeUtils.castToDate(mainValueJo.get(mainkey)));
                    mainStrBuf.append(mainkey + ",");
                } else if (null == mainValueJo.get(mainkey) || "".equals(mainValueJo.get(mainkey))) {
                } else {
                    paramList.add(mainValueJo.get(mainkey));
                    mainStrBuf.append(mainkey + ",");
                }
            }
            mainStrBuf.append("ID,AD_CLIENT_ID) VALUES(");
            for (String mainkey : mainKeySet) {
                if (null == mainValueJo.get(mainkey) || "".equals(mainValueJo.get(mainkey))) {

                }else {
                    mainStrBuf.append("?,");
                }
            }
            mainStrBuf.append("?,?)");
            paramList.add(Tools.getSequence(mainTableName));
            paramList.add(clientid);
            QueryEngine.getInstance().executeUpdate(mainStrBuf.toString(), paramList.toArray());
            //做返回
            BackSender.send(topic, tag, clientid.toString(), billNo);
        }
    }

}
